package com.ag.admin.web.loader;

import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.web.context.support.WebApplicationContextUtils;

import com.ag.admin.security.SecurityManager;
import com.ag.admin.utils.UserUtil;
import com.ag.bean.TbPermission;
import com.ag.contactTree.service.LocalTreeService;

/**
 * ServletContext监听类，用来在Servlet容器启动时执行系统角色的权限填充
 * 
 * @author 黎肇明
 * 
 */

public class ServletContextLoaderListener implements ServletContextListener {
	// @Resource(name = "LocalTreeService")
	// private LocalTreeService localTree;

	@Override
	public void contextDestroyed(ServletContextEvent servletContextEvent) {
		servletContextEvent.getServletContext().removeAttribute(
				UserUtil.ROLE_AUTHORITIES);
	}

	@Override
	public void contextInitialized(ServletContextEvent servletContextEvent) {
		ServletContext servletContext = servletContextEvent.getServletContext();
		SecurityManager securityManager = this
				.getSecurityManager(servletContext);
		Map<String, Map<String, TbPermission>> roleAuthorities = securityManager
				.loadRoleAuthorities();
		servletContext.setAttribute(UserUtil.ROLE_AUTHORITIES, roleAuthorities);
		/**
		 * 下面是载入通讯录树的
		 */
		// localTree.updateTree();
		LocalTreeService localTree = (LocalTreeService) WebApplicationContextUtils
				.getWebApplicationContext(servletContext).getBean(
						"LocalTreeService");
		localTree.updateTree();
	}

	protected SecurityManager getSecurityManager(ServletContext servletContext) {
		return (SecurityManager) WebApplicationContextUtils
				.getWebApplicationContext(servletContext).getBean(
						"securityManager");
	}

}
